package com.yhd.task.dynamic;

import com.itranswarp.compiler.JavaStringCompiler;
import com.yhd.task.model.TaskVO;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;
import java.util.Random;

/**
 * @author yhd
 * @since 2011/01/03
 * <br/>编译字节码文件生成Class实例
 */
@Component
public class CreateClass {

    private final static String packageName ="com.yhd.task.task";

    public Class<?> compile(TaskVO taskVO) {

        String code = new StringBuilder()
                .append(";import java.util.HashMap;import cn.hutool.http.HttpUtil;import net.javacrumbs.shedlock.core.SchedulerLock;import org.springframework.scheduling.annotation.Async;import org.springframework.scheduling.annotation.Scheduled; public class ")
                .append(taskVO.getClassName())
                .append("{@SchedulerLock(name = \"")
                .append(taskVO.getLockName())
                .append("\", lockAtLeastForString = \"")
                .append(taskVO.getLockAtLeastForString())
                .append("\", lockAtMostForString = \"")
                .append(taskVO.getLockAtMostForString())
                .append("\")\n@Scheduled(cron = \"")
                .append(taskVO.getCron())
                .append("\")\n@Async(\"taskExecutor\")\n public void task() {")
                .append("HashMap<String, String> headers = new HashMap<>();")
                .append("headers.put(\"xxx\", \"xxx\");")
                .append("HttpUtil.createGet(\"")
                .append(taskVO.getPath())
                .append("\").addHeaders(headers).form(null).execute().body();")
                .append("}}")
                .toString();

        String prefix = String.format("package %s", packageName);
        String fullName = String.format("%s.%s", packageName, taskVO.getClassName());
        JavaStringCompiler compiler = new JavaStringCompiler();
        System.out.println(code);
        try {
            Map<String, byte[]> results = compiler.compile(taskVO.getClassName()+ ".java", prefix + code);
            return compiler.loadClass(fullName, results);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }



}